package com.s63.controller;

import com.s63.entity.User;
import com.s63.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

    @GetMapping
    public String getPage(User user,
                          @RequestParam(required = false, defaultValue = "1") int pageNum,
                          @RequestParam(required = false, defaultValue = "2") int pageSize,
                          Model model) {
        model.addAttribute("page", userService.getPage(user, PageRequest.of(pageNum - 1, pageSize)));
        model.addAttribute("user", user);
        return "user/index";
    }

/*    @GetMapping
    public String getAll(Model model) {
        model.addAttribute("userList", userService.getAll());
        return "user/index";
    }*/

    @GetMapping("/add")
    public String add() {
        return "user/add";
    }

    @PostMapping
    public String add(User user) {
        userService.add(user);
        return "redirect:/users";
    }

    @GetMapping("/del/{id}")
    public String del(@PathVariable Integer id) {
        userService.del(id);
        return "redirect:/users";
    }

    @GetMapping("/get/{id}")
    public String get(@PathVariable Integer id, Model model) {
        model.addAttribute("user", userService.getById(id));
        return "user/update";
    }

    @PostMapping("/update")
    public String update(User user) {
        userService.update(user);
        return "redirect:/users";
    }
}
